<template>
  <VButton type="primary" @click="dialogVisible = true" class="title-btn">文件模板下载</VButton>
  <div class="row-box">
    <div v-for="(item, idx) in data" :key="idx" class="flex items-center my-[12px]" @click="onRow(idx)">
      <label>文件类型：</label>
      <el-select v-model="item.type" placeholder="请选择" style="width: 120px">
        <el-option label="PI单" value="PI" />
        <el-option label="PO单" value="PO" />
      </el-select>
      <template v-if="item.type">
        <VButton @click="addRow" class="mx-[8px]">添加</VButton>
        <el-upload
          :ref="(el) => getRef(el, idx)"
          v-model:file-list="fileList"
          class="v-import"
          :data="extraData"
          :limit="1"
          :action="ossParams.host || ''"
          :auto-upload="false"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-exceed="handleExceed"
          :on-progress="handleUploadProgress"
          :on-error="handleUploadError"
          :on-change="handleChange"
          :on-success="handleUploadSuccess"
        >
          <VButton type="primary">上传文件</VButton>
        </el-upload>
        <span class="mx-[8px]">{{ item.name }}</span>
        <el-link type="primary" :underline="false" class="mr-[12px]" @click="downloadRow(item.name)">下载</el-link>
        <el-link type="danger" :underline="false" @click="drlRow(idx)" v-if="data.length > 1">删除</el-link>
      </template>
    </div>
  </div>

  <el-dialog v-model="dialogVisible" title="文件模板下载" width="600">
    <div class="flex">
      <div class="flex-1"></div>
      <el-button type="primary" @click="tplDownloadAll"> 全部下载 </el-button>
    </div>
    <el-table :data="attachmentTplData">
      <el-table-column type="index" width="60" label="序号" />
      <el-table-column property="name" label="模板名称" />
      <el-table-column label="操作" width="100">
        <template #default="{ row, $index }">
          <el-link type="primary" :underline="false" :href="row.url">下载</el-link>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogVisible = false"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus"
import { uploadSignUrl } from "@/api/public"
import api from "./api"
const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
})

const downloadRow = (name) => {
  api.importFilepath({ filepath: `attachment/${name}` }).then((res) => {
    if (res.data.url) {
      window.open(res.data.url, "noopener", "noreferrer")
    }
  })
}

let ossParams = reactive({
  host: "",
})
const onIndex = ref(null)
const onRow = (idx) => {
  onIndex.value = idx
}

onMounted(() => {
  getTplData()
  initUpload()
})

const initUpload = async () => {
  const { data } = await uploadSignUrl({ dir: "import/attachment/" })
  ossParams = {
    ...data?.signature,
  }
}
const addRow = () => {
  props.data.push({})
}
const drlRow = (idx) => {
  props.data.splice(idx, 1)
}

const refs = ref({})
const getRef = (el, idx) => {
  refs.value[`upload_${idx}`] = el
}

const extraData = reactive({})
const uploadPercent = ref(0)

let loadings = reactive({})

const fileList = ref([])
const fileName = ref("")

const handleExceed = (files) => {
  const file = files[0]
}
const get_suffix = (name) => {
  const pos = name.lastIndexOf(".")
  let suffix = ""
  if (pos != -1) {
    suffix = name.substring(pos)
  }
  return suffix
}
const handleChange = async (file) => {
  if (fileName.value) return
  uuid.value = file.uid
  await initUpload()
  refs.value[`upload_${onIndex.value}`]?.submit()
}
const uuid = ref()
const fileNames = ref("")
const beforeUpload = async (file) => {
  if (file.size > 1024 * 1024 * 20) {
    ElMessage.warning("上传文件大小不能超过20M")
    return false
  }
  try {
    const { policy, accessid, dir, signature, callback } = ossParams || {}
    const name = `${file.name.split(".")[0]}${+new Date()}`
    const _fileName = name + get_suffix(file.name)
    fileNames.value = "import/attachment/" + _fileName
    extraData.key = dir + _fileName
    extraData.policy = policy
    extraData.OSSAccessKeyId = accessid
    extraData.signature = signature
    // fileName.value = _fileName
    fileName.value = name + get_suffix(file.name)
    return true
  } catch (err) {
    fileName.value = ""
    console.log(err)
    ElMessage.error(err.message)
    return false
  }
}

const handleUploadProgress = (e) => {
  console.log("handleUploadProgress")
}
const importForm = ref({})
const handleUploadSuccess = (res, file, fileList) => {
  ElMessage.success("上传成功")
  refs.value[`upload_${onIndex.value}`]?.clearFiles()

  props.data[onIndex.value].name = fileName.value
  nextTick(() => {
    uuid.value = ""
    fileName.value = ""
  })
}
const handleUploadError = (err) => {
  fileName.value = ""
  uuid.value = ""
  ElMessage.error(`上传失败 ${err.toString()}`)
  uploadPercent.value = 0
}

const dialogVisible = ref(false)
const attachmentTplData = ref([])
const getTplData = async () => {
  const { data } = await api.attachmentTpl()
  attachmentTplData.value = data
}
const tplDownloadAll = () => {
  attachmentTplData.value.forEach((v) => {
    window.open(v.url, "noopener", "noreferrer")
  })
}
</script>
<style lang="scss" scoped>
.title-btn {
  position: absolute;
  top: 12px;
  left: 120px;
}
.row-box {
  margin-top: 12px;
  border-top: 1px solid var(--base-border-color);
}
</style>
